package com.myhexin.demo.ignite.test.base;

import com.myhexin.demo.ignite.model.po.Person;
import org.apache.ignite.Ignition;
import org.apache.ignite.cache.query.FieldsQueryCursor;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.client.IgniteClient;
import org.apache.ignite.configuration.ClientConfiguration;

import java.util.List;

/**
 * @author zhangzhonglv@myhexin.com
 * @date 2025/8/21
 */
public class SQLDemo {

    private static final String IGNITE_ADDR = "127.0.0.1:10800";

    public static void main(String[] args) {
        ClientConfiguration cfg = new ClientConfiguration();
        cfg.setAddresses(IGNITE_ADDR);
        try (IgniteClient client = Ignition.startClient(cfg)) {
            // 创建表
            client.query(new SqlFieldsQuery(String.format(
                    "CREATE TABLE IF NOT EXISTS Person (id INT PRIMARY KEY, name VARCHAR) WITH \"VALUE_TYPE=%s\"",
                    Person.class.getName())).setSchema("PUBLIC")).getAll();

            // 插入数据
            int key = 1;
            // Person val = new Person(key, "Person 1");
            // client.query(new SqlFieldsQuery("INSERT INTO Person(id, name) VALUES(?, ?)").setArgs(val.getId(), val.getName())
            //         .setSchema("PUBLIC")).getAll();

            // 查询数据
            // FieldsQueryCursor<List<?>> cursor = client
            //         .query(new SqlFieldsQuery("SELECT id,name from PERSON WHERE id=?").setArgs(key).setSchema("PUBLIC"));
            FieldsQueryCursor<List<?>> cursor = client
                    .query(new SqlFieldsQuery("SELECT id,name from Person").setArgs(key).setSchema("PUBLIC"));
            // Get the results; the `getAll()` methods closes the cursor; you do not have to
            // call cursor.close();
            List<List<?>> results = cursor.getAll();
            results.forEach(columns -> {
                System.out.println("results:" + columns);
            });
        }
    }
}
